package com.tqyan.start.controller;

import com.tqyan.model.Result;
import com.tqyan.model.controller.request.ChatRequest;
import com.tqyan.model.controller.response.CopyInfoResp;
import com.tqyan.model.mapping.CopyInfoAssembler;
import com.tqyan.service.service.InfoService;
import com.tqyan.service.transfer.FileService;
import com.tqyan.service.transfer.LimitService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @description 文案信息API
 * <p> <功能详细描述> </p>
 *
 * @author 陈晨
 * @date 2023/4/11 17:20
 */
@RestController
@RequestMapping("/info/")
@Slf4j
//@Api(tags = "文案信息API")
public class InfoController {

    @Autowired
    private CopyInfoAssembler copyInfoAssembler;
    @Autowired
    private InfoService infoService;
    @Autowired
    private FileService fileService;
    @Autowired
    private LimitService limitService;

    @GetMapping("/init")
//    @ApiOperation(value = "初始化")
    public Result<CopyInfoResp> getPoint() {
//        log.info("[文案信息] 初始化");
        try {
            infoService.init();
            return Result.success();
        } catch (Exception e) {
            log.error("[文案信息] 初始化, 异常: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    @GetMapping("/getPoint/{type}")
//    @ApiOperation(value = "获取会话指引")
    public Result<CopyInfoResp> getPoint(@PathVariable Integer type) {
//        log.info("[文案信息] type={}, 获取会话指引", type);
        try {
            return Result.success(copyInfoAssembler.convert(infoService.getPoint(type)));
        } catch (Exception e) {
            log.error("[文案信息] type={}, 获取会话指引, 异常: {}"
                    , type, e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    @GetMapping("/getTips")
//    @ApiOperation(value = "获取小贴士")
    public Result<CopyInfoResp> getTips() {
//        log.info("[文案信息] 获取小贴士");
        try {
            return Result.success(copyInfoAssembler.convert(infoService.getTips()));
        } catch (Exception e) {
            log.error("[文案信息] 获取小贴士, 异常: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    @GetMapping("/getShare")
//    @ApiOperation(value = "获取分享")
    public Result<CopyInfoResp> getShare() {
//        log.info("[文案信息] 获取分享");
        try {
            return Result.success(copyInfoAssembler.convert(infoService.getShare()));
        } catch (Exception e) {
            log.error("[文案信息] 获取分享, 异常: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    @GetMapping("/getShare/{type}")
//    @ApiOperation(value = "获取分享")
    public Result<CopyInfoResp> getShareByType(@PathVariable String type) {
        if ("501".equals(type)) {
            CopyInfoResp resp = new CopyInfoResp();
            resp.setContent("您的账户余额不足，邀请新用户登录即可获得1元奖励！");
            return Result.success(resp);
        }
        return Result.success();
    }

    @PostMapping("/getChatShare")
//    @ApiOperation(value = "获取会话分享")
    public Result<CopyInfoResp> getChatShare(@RequestBody ChatRequest chatRequest) {
        if (null == chatRequest
                || StringUtils.isBlank(chatRequest.getOpenId())
                || null == chatRequest.getChatId()
                || null == chatRequest.getChatContentId()) {
            return Result.fail("请求参数不可为空");
        }
//        log.info("[会话] chatRequest={}, 获取会话分享", chatRequest);
        boolean isLock = limitService.lock(chatRequest.getOpenId());
        if (!isLock) {
            return Result.fail("让小燕子休息一会吧");
        }
        try {
            return Result.success(copyInfoAssembler.convert(infoService.getChatShare(
                    chatRequest.getOpenId(), chatRequest.getChatId(), chatRequest.getChatContentId())));
        } catch (Exception e) {
            log.error("[会话] chatRequest={}, 获取会话分享, 异常: {}"
                    , chatRequest, e.getMessage(), e);
            return Result.fail(e.getMessage());
        } finally {
            limitService.unlock(chatRequest.getOpenId());
        }
    }

    @RequestMapping("/image/{fileName}")
    public Object download(HttpServletResponse response, @PathVariable String fileName) {
        try {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            fileService.downloadAliyunOSS(response.getOutputStream(), FileService.FOLDER_SHARE_ORIGINAL, fileName);
            return null;
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @RequestMapping("/image/thumbnail/{fileName}")
    public Object downloadThumbnail(HttpServletResponse response, @PathVariable String fileName) {
        try {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            fileService.downloadAliyunOSS(response.getOutputStream(), FileService.FOLDER_SHARE_THUMBNAIL, fileName);
            return null;
        } catch (Exception e) {
            return e.getMessage();
        }
    }

}


